import base64
import os

import gradio as gr
from sdk.httpclient import CTClientBuilder, CTClient

base_url = "https://ai-global.ctapi.ctyun.cn"

client: CTClient


def text_sentiment(text):
    url = f"{base_url}/v1/aiop/api/2gyv07uqvroc/text/textanalyse/api/sentiment"
    response = client.request("POST", url, body={"data": text})
    response.raise_for_status()
    response_json = response.json()
    try:
        return response_json['returnObj']
    except:
        return response_json


def text_correct(text):
    url = f"{base_url}/v1/aiop/api/2grogewxrdwk/nlp/text-correct"
    response = client.request("POST", url, body={"data": text})
    response.raise_for_status()
    response_json = response.json()
    try:
        return response_json['returnObj']
    except:
        return response_json


def text_opinion(cate, text):
    url = f"{base_url}/v1/aiop/api/2gyuqiiopt6o/text/textanalyse/api/textopinion"
    response = client.request("POST", url, body={"data": {"cate": cate, "text": text}})
    response.raise_for_status()
    response_json = response.json()
    try:
        return response_json['returnObj']
    except:
        return response_json


def tts(text: str, voice_type: int, pitch: float, speed: float, volume: int):
    url = f"{base_url}/v1/aiop/api/2z0yhhrzgv0g/tts/predict"
    req_body = {
        "Action": "TTS",
        "TextData": text,
        "VoiceType": voice_type,
        "Pitch": pitch,
        "Speed": speed,
        "Volume": volume,
    }
    print(f"tts request body: {req_body}")
    response = client.request("POST", url, body=req_body)
    response.raise_for_status()
    response_json = response.json()
    try:
        audio_base64 = response_json['returnObj']['Audio']
        audio_wav = base64.urlsafe_b64decode(audio_base64)
        return audio_wav
    except:
        print(f"tts error response: {response_json}")
        raise


gr_config = {
    "text_sentiment": gr.Interface(fn=text_sentiment,
                                   inputs="text",
                                   outputs="text",
                                   examples=[
                                       "今天天气不错。",
                                       "非常不错的说，服务态度特别好，有朋友有需要的话，一定会推荐的。",
                                       "网红景点果然一般，没什么好看的。"
                                   ],
                                   title="自然语言处理（公测）- 情感分析",
                                   description="对带有情感色彩的主观性文本进行推理与分析，自动进行文本情感倾向性判断，输出该文本的情感极性类别，情感极性分为积极、消极。",
                                   article="进一步了解天翼云自然语言处理产品：<a href='https://www.ctyun.cn/products/nlp'>https://www.ctyun.cn/products/nlp</a>"),
    "text_correct": gr.Interface(fn=text_correct,
                                 inputs="text",
                                 outputs="text",
                                 examples=[
                                     "我昨天去图书馆借了一本《哈姆雷特》，书里的故事非常精采。",
                                     "这部电影的剧情非常紧凑，让人目不遐接。",
                                     "这道菜的味道真是美位，让人回味无穷。"
                                 ],
                                 title="自然语言处理（公测）- 文本纠错",
                                 description="针对一段文本，自动识别纠正其中的语法或字词错误，包括形似字、音似字，漏字等文法错误的纠正和探测。",
                                 article="进一步了解天翼云自然语言处理产品：<a href='https://www.ctyun.cn/products/nlp'>https://www.ctyun.cn/products/nlp</a>"),
    "text_opinion": gr.Interface(fn=text_opinion,
                                 inputs=[
                                     gr.Dropdown(["hotel", "catering", "shopping"], label="cate"),
                                     gr.Textbox(label="text")
                                 ],
                                 outputs="text",
                                 examples=[
                                     [
                                         "hotel",
                                         "前台的服务态度很好，麻烦了她们很多次都很乐意帮忙，不过房间里设施也太老旧了，最近还涨价了，性价比略低。"
                                     ],
                                     [
                                         "catering",
                                         "环境很不错，不愧是老店~服务热情，倒车停车还有工作人员主动帮忙，三文鱼尤其好吃，五星好评。"
                                     ],
                                     [
                                         "shopping",
                                         "新买的机械键盘，用起来可以说非常顺手了，质量一级棒，不过物流也太慢了吧，卖家考虑换一家快递公司吧。"
                                     ]
                                 ],
                                 title="自然语言处理（公测）- 商品评价解析",
                                 description="智能解析评论文本内容，进行评论观点的抽取与分析，自动输出评论观点标签及评论观点极性，将文本转化为结构化的属性字段。",
                                 article="进一步了解天翼云自然语言处理产品：<a href='https://www.ctyun.cn/products/nlp'>https://www.ctyun.cn/products/nlp</a>"),
    "tts": gr.Interface(fn=tts,
                        inputs=[
                            gr.Textbox(label="text", value="春天的花开，唤醒了大地的生机"),
                            gr.Dropdown([("甜美女声", 2), ("温柔女声", 3), ("磁性男声", 4), ], label="voice type"),
                            # ("男声（旧）", 0),("女声（旧）", 1), 但建议使用新版本
                            gr.Number(value=1.0, minimum=0.8, maximum=2, step=0.1, label="语调。范围：[0.8, 2]，默认：1.0"),
                            gr.Number(value=1.0, minimum=0.5, maximum=2, step=0.1, label="语速。范围：[0.5, 2]，默认：1.0"),
                            gr.Number(value=0, minimum=-5, maximum=5, step=1, precision=0,
                                      label="音量。范围：[-5, 5]，-5并非表示无声，默认：0"),
                        ],
                        outputs=gr.Audio(label="audio", autoplay=True),
                        examples=[
                        ],
                        title="自然语言处理（公测）- 语音合成",
                        description="语音合成（Text To Speech，TTS）将文本转成拟人化的语音。目前仅支持中文语音合成，提供男、女两种色的选择，支持自定义语调、语速等参数。",
                        article="进一步了解天翼云自然语言处理产品：<a href='https://www.ctyun.cn/products/nlp'>https://www.ctyun.cn/products/nlp</a>"),
}


def get_not_empty_env(key):
    value = os.getenv(key, "").strip()
    if value == "":
        raise Exception(f"env {key} is not set or empty")
    return value


def run():
    ctyun_ak = get_not_empty_env("ext_cf_ctyun_ak")
    ctyun_sk = get_not_empty_env("ext_cf_ctyun_sk")
    ctyun_ai_app_key = get_not_empty_env("ext_cf_ctyun_ai_app_key")
    nlp_type = get_not_empty_env("ext_cf_nlp_type")

    global client
    client = CTClientBuilder().with_ak(ctyun_ak).with_sk(ctyun_sk).with_ai_app_key(ctyun_ai_app_key).build()

    gr_config[nlp_type].launch(server_name="0.0.0.0", server_port=9000)


if __name__ == '__main__':
    run()
